package com.bizmda.bizsip.sample.source.longtcpnetty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 史正烨
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    private SampleServerService serverService;
    public NettyServerHandler(SampleServerService serverService) {
        super();
        this.serverService = serverService;
    }

    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("Channel通道激活:{}-{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
    }


    /**
     * 取消绑定
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("Channel通道失效:{}-{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                log.info("读空闲超时，主动关闭连接！");
                //主动关闭连接
                ctx.channel().close();
            }
        }

        super.userEventTriggered(ctx, evt);
    }
        /**
         * 客户端发消息会触发
         */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //TODO:TCP传输过程中的分包拆包问题有待后期解决，建议采用添加不同解码器的方式来处理
        this.serverService.process((SampleMessage) msg);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
